<template>
    <div class="Login">
        <el-form :model="loginUser"
                 label-position="top"
                 :rules="rules"
                 ref="loginUser"
                 hide-required-asterisk
                 status-icon>
            <el-form-item prop="username">
                <el-input v-model="loginUser.username" placeholder="请输入注册邮箱或手机号" clearable autofocus>
                    <template slot="prepend">登录凭证</template>
                </el-input>
            </el-form-item>
            <el-form-item prop="password">
                <el-input v-model="loginUser.password" placeholder="请输入密码" show-password clearable>
                    <template slot="prepend">登录密码</template>
                </el-input>
            </el-form-item>
            <el-form-item>
                <el-button style="width: 100%" type="primary" @click="login('loginUser')">登录</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
    import axios from 'axios'
    import MD5 from 'js-md5'
    import QS from 'qs'

    export default {
        name: "Login",
        data() {

            return {
                loginUser: {
                    username: "",
                    password: "",
                },
                rules: {
                    username:
                        [
                            {required: true, message: '请输入注册邮箱', trigger: 'blur'},
                            {type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur']},
                        ],
                    password:
                        [
                            {required: true, message: '请输入登录密码', trigger: 'blur'}
                        ]
                }

            }
        },
        created() {
            this.clearForm()
        },
        methods: {
            login(loginUser) {
                let _this = this
                this.$refs[loginUser].validate((valid) => {
                    if (valid) {
                        axios({
                                method: 'post',
                                url: '/wecs/form/token',
                                headers: {
                                    'content-type': 'application/x-www-form-urlencoded',
                                    'Authorization': 'Basic MTIzNDU2OlFXRWFzZDEyMw=='
                                },
                                data: QS.stringify(
                                    {
                                        grant_type: 'password',
                                        username: _this.loginUser.username,
                                        password: MD5(_this.loginUser.password)
                                    }
                                )
                            }
                        ).then(res => {
                            const data = res.data;
                            if (res.status === 200) {
                                const token = data.access_token;
                                localStorage.setItem("token", token)
                                //加载用户数据后跳转到首页
                                this.getUserInfo(token);
                            } else {
                                //用户名或密码错误
                                this.$message.error("登录异常");
                            }
                        }).catch(err => {
                            const resStatus = err.response.status;
                            if (resStatus === 401) {
                                this.$message.error("登陆失败，用户名或密码错误");
                            }
                        })

                    } else {
                        return false;
                    }
                })
            },
            getUserInfo(token) {
                axios({
                        method: 'get',
                        url: '/wecs/user/info',
                        headers: {
                            'Authorization': 'bearer ' + token
                        }
                    }
                ).then(res => {
                        const userData = res.data
                        if (userData.code === 2000) {
                            this.$message({
                                message: '登录成功',
                                type: 'success'
                            });
                            localStorage.setItem("user", JSON.stringify(userData.data))
                            this.$router.push({name: "ShowLink"})
                        } else {
                            //登录失败
                            localStorage.removeItem("token")
                            localStorage.removeItem("user")
                            this.$message.error(userData.message);
                        }
                    }
                ).catch(err => {
                        console.log(err.response.status)
                    }
                )
            },
            clearForm() {
                this.loginUser = {
                    username: "",
                    password: ""
                }
            }
        }
    }
</script>

<style scoped>

    .Login {

    }
</style>